<?php
//$_GET['id']
//$_GET['order']={title|state|create|edit}

	include 'include/function.php';
	include_once 'include/grouplist.php';
	
	$shownode_id=-1;
	if(isset($_GET['id']))$shownode_id=get_to_mysql($_GET['id']);
	if($shownode_id!=-1){
		$query="select *,LENGTH(description) as des_len from node where id=$shownode_id";
		$ret=oj_query($query);
		$row=mysql_fetch_assoc($ret);
		if(!isset($row['id']))redirect_error(sprintf(_d('err_no_nodeD'),$shownode_id));
		
		$shownode_parent=$row['parent'];
		$shownode_locked=($row['has_question']!='no');
		$shownode_freeze=($row['freezed']=='yes');
	}
	//权限
	$shownode_perm=permission_node($_user_id,$shownode_id);
	if(!isset($shownode_perm[0]))need_login();
	//评级
	if(isset($_user_id) && $shownode_id!=-1 && isset($shownode_perm[0])) {
		$shownode_user_rate=get_user_rate($_user_id,$shownode_id);
		if(!isset($shownode_user_rate[0])) {
			oj_query('insert into user_rate (user_id, node_id, visit_time) '
				. "values ($_user_id, $shownode_id, now()) ");
			$shownode_rate='view';
		} else {
			set_user_rate($_user_id,$shownode_id);
			$shownode_rate=$shownode_user_rate[0];
		}
	}


function get_node_state($row) {
	global $_user_id;
	$state=array();
	if($row['has_question']!='no') {
		$now_perm=permission_node($_user_id,$row['id']);
		if(strpos($now_perm[0],'view')===false) {
			if(exist_question($row['id'],'view'))array_push($state,_d('sn_locked_question'));
			else array_push($state,_d('sn_locked'));
		} else {
			if($row['has_question']=='view') array_push($state,_d('sn_free_view'));
			else array_push($state,_d('sn_unlocked'));
		}
	}
	if($row['freezed']=='yes')array_push($state,_d('sn_frozen'));
	return implode('&nbsp;',$state);
}

function draw_children($now_id,$user_id,$order) {
//order
	if($order=='title')$query_order='order by title asc ';
	else if($order=='state')$query_order='order by has_question asc, freezed asc ';
	else if($order=='create')$query_order='order by create_time desc ';
	else if($order=='edit')$query_order='order by modify_time desc ';
	else $query_order='order by title asc ';
	
	if(empty($user_id)) {
		$query = 'select id,title,description="" as is_empty,child_count,create_time,modify_time,has_question,freezed '
				. "from node where parent=$now_id $query_order";
		$ret=oj_query($query);
		while($row=mysql_fetch_assoc($ret)) {
			$now_title = htmlspecialchars($row['title']);
			if($row['is_empty'])$now_empty='style="color:#d00;" title="empty"'; else $now_empty='';
			echo '<tr>';
				echo "<td>&nbsp;<a href='shownode.php?id={$row['id']}' $now_empty>$now_title</a>({$row['child_count']})</td>";
				echo '<td align="center">' . get_node_state($row) . '</td>';
				echo "<td align=\"center\">{$row['create_time']}</td>";
				echo "<td align=\"center\">{$row['modify_time']}</td>";
			echo '</tr>';
		}
	} else {
		$query = 'select node.id as id, node.title as title, node.child_count as child_count, node.create_time as create_time, '
			. 'node.modify_time as modify_time, node.has_question as has_question, node.freezed as freezed, description="" as is_empty, '
			. '(user_rate.visit_time < node.modify_time) as is_new, (user_rate.visit_time < node.child_update_time) as is_update '
			. "from node left join user_rate on node.id=user_rate.node_id and user_rate.user_id=$user_id "
			. "where node.parent=$now_id $query_order ";
		$ret=oj_query($query);
		while($row=mysql_fetch_assoc($ret)) {
			$now_title = htmlspecialchars($row['title']);
			if($row['is_empty'])$now_empty='style="color:#d00;" title="empty"'; else $now_empty='';
			echo '<tr>';
				echo "<td>&nbsp;<a href='shownode.php?id={$row['id']}' $now_empty>$now_title</a>({$row['child_count']})";
					if($row['is_new'] || is_null($row['is_new'])) echo '<span style="color:red">new!</span>';
					else if($row['is_update']) echo '<span style="color:red">update!</span>';
				echo '</td>';
				echo '<td align="center">' . get_node_state($row) . '</td>';
				echo "<td align=\"center\">{$row['create_time']}</td>";
				echo "<td align=\"center\">{$row['modify_time']}</td>";
			echo '</tr>';
		}
	}
}

function draw_tr2($left,$right) {
	echo "<tr><td>$left</td><td>$right</td></tr>";
}

function draw_icon($row,$col,$addition='') {
	$left=-$col*32;
	$top=-$row*32;
	printf('<div class="icon32 i_permission" style="background-position:%dpx %dpx;" %s></div>',$left,$top,$addition);
}

function get_order_title($order) {
	global $shownode_id;
	if($order==$_GET['order'])return _d('n_' . $order);
	else return "<a href='shownode.php?id=$shownode_id&order=$order'>" . _d('n_' . $order) . '</a>';
}

function draw_requests($condition,$is_super) { //$condition="where .."
	global $shownode_url;
	$query='select request_id,user_id,level,reason,submit_time,state from request_permit ' . $condition;
	$ret=oj_query($query);
	$n_request=0;
	while($row=mysql_fetch_assoc($ret)) {
		$shownode_request[$n_request]=$row;
		$shownode_request[$n_request]['user']=user_id_to_name($row['user_id']);
		$n_request++;
	}
	if($n_request>0) {
		echo _d('request_list') . '<br>';
		draw_tablelist_head(array(
			_d('request_user'),
			_d('request_level'),
			array(_d('request_reason'),'width=60%'),
			_d('request_submit_time'),
			($is_super?_d('request_action'):_d('request_state'))
		));
		$i=0;
		while($i<$n_request) {
			echo '<tr>';
				echo "<td align=\"center\">{$shownode_request[$i]['user']}</td>";
				echo "<td align=\"center\">{$shownode_request[$i]['level']}</td>";
				echo '<td>' . htmlspecialchars($shownode_request[$i]['reason']) . '</td>';
				echo "<td align=\"center\">{$shownode_request[$i]['submit_time']}</td>";
			if($is_super) {
				echo '<td align="center">';
					echo "<a href='owner_action.php?url=$shownode_url&action=request_ac&request_id={$shownode_request[$i]['request_id']}'>Accept</a>&nbsp;";
					echo "<a href='owner_action.php?url=$shownode_url&action=request_de&request_id={$shownode_request[$i]['request_id']}'>Deny</a>&nbsp;";
				echo '</td>';
			} else {
				echo "<td align=\"center\">{$shownode_request[$i]['state']}</td>";
			}
			echo '</tr>';
			$i++;
		}
		echo '</table>';
	}
}

function quant_word_s($val,$div,$word) {
	$val=($val-($val%$div))/$div;
	if($val>1)return $val . _d('time_' . $word . 's');
	return $val . _d('time_' . $word);
}

function nice_time($old_time) {
	$time_day=24*60*60;
	$now_time=time();
	$now_day =$now_time-($now_time%$time_day);
	$old_day =$old_time-($old_time%$time_day);
	if($now_day-$old_day<=3*$time_day){
		if($now_day==$old_day){
			$delta_second=$now_time-$old_time;
			if($delta_second<60*60) {
				if($delta_second<60) {
					return quant_word_s($delta_second, 1, 'second') . _d('time_ago');
				} else {
					return quant_word_s($delta_second, 60, 'minute') . _d('time_ago');
				}
			} else {
				return quant_word_s($delta_second, 60*60, 'hour') . _d('time_ago');
			}
		} else {
			return quant_word_s($now_day-$old_day, $time_day, 'day') . _d('time_ago') . date('H:n:s', $old_time);
		}
	} else {
		return date('Y-m-d H:n:s', $old_time);
	}
}

function exist_question($node,$level) {
	$ret=oj_query("select question_id from question where node_id=$node and level='$level' limit 1");
	$row=mysql_fetch_row($ret);
	return isset($row[0]);
}

//-------------------------------------------------------------------------
	
	$shownode_url=urlencode($_SERVER['REQUEST_URI']);
	if(!isset($shownode_perm[0])) { //can't view
		if(exist_question($shownode_perm[1],'view')) //有题目时直接过去
			redirect("request_permission.php?id={$shownode_perm[1]}&type=question&level=view");

		$page_title=$site_title . ' - Access denied';
		include 'include/header.php';
		echo '<div class="problem_content">';
			echo '<center><p>' . sprintf(_d('sn_not_permitted'),$shownode_id) . '</p></center>';
			echo '<p>' . _d('sn_try_solution') . '</p>';
			echo '<ul>';
				if($shownode_perm[1]==$shownode_id) {
					//answer questions, or request permission
					echo '<li>' . sprintf(_d('sn_answer_question'),$shownode_id) . '</li>';
					echo '<li>' . sprintf(_d('sn_view_parent'),$shownode_perm[2]) . '</li>';
				} else {
					echo "<li>Try <a href='shownode.php?id={$shownode_perm[1]}'>node-{$shownode_perm[1]}</a> to get permission.</li>";
				}
			echo '</ul>';
		echo '</div>';
		//查看已经提交的请求
		draw_requests("where node_id=$shownode_id && user_id=$_user_id order by submit_time ", 0);
		echo '<center><a href="javascript:history.go(-1)">Go back</a></center>';
	} else {
		if($shownode_id==-1){
			$page_title=$site_title . ' - Node root';
			include 'include/header.php';
		} else {
			$now_title = htmlspecialchars($row['title']);
			$page_title=$site_title . ' - ' . $now_title;
			include 'include/header.php';

			echo '<div class="problem_content">';
				//-----节点信息栏-----//
				echo '<div style="float:right;">';
					echo '<a style="float:right;" onclick=\'toggleBox("shownode_sidebox");\'>' . _d('sn_sidebox_detail') . '</a>';
					echo '<table id="shownode_sidebox" style="clear:right;"><tbody>';
						draw_tr2(_d('n_id'),		$shownode_id);
						if(isset($shownode_rate)) {
							echo '<tr><td>' . _d('sn_rate') . '</td>';
							echo '<td>';
								echo '<select id="shownode_rate_combo" style="font-size:1em;" ' .
									"onChange='sendRate(this,$shownode_id)'>";
								foreach($rate_array as $key=>$val){
									echo "<option value='$key'";
									if($shownode_rate==$key)echo ' selected="selected"';
									echo '>' . _d($val) . '</option>';
								}
								echo '</select>';
								echo '<br/><span id="shownode_rate_state" style="display:none;"></span>';
							echo '</td></tr>';
						}
						echo "<tr><td colspan=\"2\" align=\"center\"><a onclick='toggleRateDetail($shownode_id)'>" . _d('sn_rate_detail');
						echo '</a><div id="shownode_rate_detail" style="display:none;"></div></td></tr>';
						draw_tr2(_d('n_view'),		$row['visit_count']+1);
						draw_tr2(_d('n_length'),	$row['des_len'] . 'B');
						draw_tr2(_d('n_create'),	nice_time(strtotime($row['create_time'])));
						draw_tr2(_d('n_edit'),		nice_time(strtotime($row['modify_time'])));
						draw_tr2(_d('n_update'),	nice_time(strtotime($row['child_update_time'])));
						draw_tr2(_d('n_creator'),	user_id_to_name_link($row['create_id']));
						draw_tr2(_d('n_editor'),	user_id_to_name_link($row['modify_id']));
						draw_tr2(_d('n_state'),	get_node_state($row));
						if(strstr($shownode_perm[0],'super')) {
							if($shownode_freeze) {
								draw_tr2(_d('sn_owner'),"<a href='owner_action.php?url=$shownode_url&action=unfreeze&node_id=$shownode_id'>" . _d('sn_do_unfreeze') . '</a>');
							} else {
								draw_tr2(_d('sn_owner'),"<a href='owner_action.php?url=$shownode_url&action=freeze&node_id=$shownode_id'>" . _d('sn_do_freeze') . '</a>');
							}
						}
						echo '<tr><td>' . _d('sn_perm') . '</td><td>';
						$shownode_can_apply = isset($_user_id) && $shownode_locked;
						$i=0;
						foreach($level_array as $key=>$val){
							if(strstr($shownode_perm[0],$key)) {
								draw_icon(0,$i,"title='$key' ");
							} else if($shownode_can_apply) {
								echo "<a title='Apply for $key' href='request_permission.php?id=$shownode_id&type=question&level=$key'>";
								draw_icon((exist_question($shownode_id,$key)?2:1),$i);
								echo '</a>';
							} else {
								draw_icon(1,$i,"title='$key' ");
							}
							$i++;
						}
						echo '</td></tr>';
					echo '</tbody></table>';
				echo '</div>';
				//-----父节点们-----//
				draw_parents($shownode_parent);
				echo "$now_title({$row['child_count']})";
				if($shownode_freeze || !strstr($shownode_perm[0],'modify')) {
					echo '<span>[<font color="gray">' . _d('sn_edit') . '</font>]</span><br>';
				} else {
					echo "<span>[<a href='editnode.php?id=$shownode_id'>" . _d('sn_edit') . '</a>]</span><br>';
				}
				//-----标题和内容-----//
				echo '<center>';
					echo "<div class='subtitle'>$now_title</div>";
				echo '</center>';
				echo '<div id="main_content">';
					echo expand_include($shownode_id,$row['description']);
				echo '</div>';
				echo '<div style="clear:both;"></div>';
			echo '</div>';
			
			$query="update node set visit_count=visit_count+1 where id=$shownode_id ";
			$ret=oj_query($query);
		}
		
		//-----子节点列表-----//
		draw_tablelist_head(array(
			array(get_order_title('title'),'width=60%'),
			get_order_title('state'),
			get_order_title('create'),
			get_order_title('edit')
		));
		
		draw_children($shownode_id,$_user_id,$_GET['order']);
		if(strstr($shownode_perm[0],'add')) {
			echo "<tr><td colspan=\"4\"><a href='addnode.php?parent=$shownode_id'>" . _d('sn_add') . '</a></td></tr>';
		}
		echo '</table>';
		
		//-----所属组列表-----//
		if($shownode_id>0)draw_group_list(GL_NODE_GROUP_LIST,0,$shownode_id);
		
		//-----申请列表-----//
		if(strstr($shownode_perm[0],'super')){
			//待处理的申请权限的条目：
			draw_requests("where node_id=$shownode_id && state='pending' order by submit_time asc limit 20 ", 1);
		}
		
		//-----操作列表-----//
		if($shownode_id!=-1) {
			echo '<center>';
			if(strstr($shownode_perm[0],'delete')) {
				//删除节点
				$shownode_parent_perm=permission_node($_user_id,$shownode_parent);
				if(strstr($shownode_parent_perm[0],'add')) {
					echo "[<a href='deletenode.php?id=$shownode_id&confirm=1'>" . _d('sn_delete') . '</a>]&nbsp;';
				}
				//移动节点
				echo '[' . _d('sn_move') . '<form method="get" action="movenode.php" style="display:inline">';
					echo '<input type="hidden" name="confirm" value="1" />';
					echo "<input type='hidden' name='id' value='$shownode_id' />";
					echo '<input name="parent" size="6" />';
					echo '<input type="submit" value="Go" />';
				echo '</form>]&nbsp;';
			}
			//查看提问（locked节点才有）
			if($shownode_locked)
				echo "[<a href='showquestion.php?id=$shownode_id'>" . _d('sn_question') . '</a>]&nbsp;';
			//导出
			echo "[<a href='export.php?id=$shownode_id'>" . _d('sn_export') . '</a>]&nbsp;';
			//历史版本
			echo "[<a href='history.php?id=$shownode_id&type=node'>" . _d('sn_revision') . '</a>]&nbsp;';
			echo '</center>';
		}
	}

	include 'include/footer.php';
?>

